package csrc

import (
	"fmt"
	s "gitee.com/gcom/stockdock/core/support"
	"gitee.com/gcom/stockdock/spider/csrc"
)

// 更新深交所A股列表
func UpdateStockListSz(ctx s.TracerCtx) error {
	// 上交所主板
	list, err := csrc.ListSzse(ctx)
	if err != nil {
		s.WriteErrEvent(ctx, "下载深交所主板股票列表失败", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("获取深交所主板股票%d条", len(list)))
	if err = updateList(ctx, list); err != nil {
		return err
	}
	return nil
}

// 更新上交所A股列表
func UpdateStockListSh(ctx s.TracerCtx) error {
	// 上交所主板
	list, err := csrc.ListSse(ctx)
	if err != nil {
		s.WriteErrEvent(ctx, "下载上交所主板股票列表失败", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("获取上交所主板股票%d条", len(list)))
	if err = updateList(ctx, list); err != nil {
		return err
	}

	list, err = csrc.ListKcb(ctx)
	if err != nil {
		s.WriteErrEvent(ctx, "下载上交所科创板股票列表失败", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("获取上交所科创板股票%d条", len(list)))
	if err = updateList(ctx, list); err != nil {
		return err
	}
	return nil
}

func updateList(ctx s.TracerCtx, list []*csrc.Stock) error {
	entities := make([]*csrc.StockEntity, 0, len(list))
	for _, v := range list {
		entities = append(entities, &csrc.StockEntity{Stock: v})
	}
	if _, err := csrc.UpdateStockList(ctx.DB, entities); err != nil {
		s.WriteErrEvent(ctx, "写入股票异常", err)
		return err
	}
	s.WriteEvent(ctx, fmt.Sprintf("写入股票%d条", len(list)))
	return nil
}
